(function initContentJs() {
  // 引入jq
  const jqJsPath = 'js/jquery-3.3.1.min.js';
  const jqScript = document.createElement('script');
  jqScript.setAttribute('type', 'text/javascript');
  jqScript.setAttribute('charset', 'utf-8');
  jqScript.src = chrome.extension.getURL(jqJsPath);
  
  // 引入复制js
  const copyPath = 'js/clipboard.min.js';
  const copyScript = document.createElement('script');
  copyScript.setAttribute('type', 'text/javascript');
  copyScript.setAttribute('charset', 'utf-8');
  copyScript.src = chrome.extension.getURL(copyPath);

  // 引入二维码js
  const qrCodePath = 'js/qrcode.min.js';
  const qrCodeScript = document.createElement('script');
  qrCodeScript.setAttribute('type', 'text/javascript');
  qrCodeScript.setAttribute('charset', 'utf-8');
  qrCodeScript.src = chrome.extension.getURL(qrCodePath);

  // 引入css样式
  const cssPath = 'css/style.css';
  const head = document.getElementsByTagName('head')[0];
  const linkTag = document.createElement('link');
  linkTag.href = chrome.extension.getURL(cssPath);
  linkTag.setAttribute('rel','stylesheet');
  linkTag.setAttribute('charset','utf-8');
  linkTag.setAttribute('type','text/css');

  // 引入html
  const hjsPath = 'js/content-html.js';
  const hscript = document.createElement('script');
  hscript.setAttribute('type', 'text/javascript');
  hscript.setAttribute('charset', 'utf-8');
  hscript.src = chrome.extension.getURL(hjsPath);

  // 引入html相关js
  const jsPath = 'js/content-script.js';
  const script = document.createElement('script');
  script.setAttribute('type', 'text/javascript');
  script.setAttribute('charset', 'utf-8');
  script.src = chrome.extension.getURL(jsPath);

  // 引入layer
  const layjsPath = 'plugin/layer/layer.js';
  const layscript = document.createElement('script');
  layscript.setAttribute('type', 'text/javascript');
  layscript.setAttribute('charset', 'utf-8');
  layscript.src = chrome.extension.getURL(layjsPath);
  
  // 引入datepicker
  const datejsPath = 'plugin/datepicker/bootstrap-datepicker.js';
  const dateScript = document.createElement('script');
  dateScript.setAttribute('type', 'text/javascript');
  dateScript.setAttribute('charset', 'utf-8');
  dateScript.src = chrome.extension.getURL(datejsPath);

  // 引入验证相关js
  const validJsPath = 'js/jquery.valid.js';
  const validScript = document.createElement('script');
  validScript.setAttribute('type', 'text/javascript');
  validScript.setAttribute('charset', 'utf-8');
  validScript.src = chrome.extension.getURL(validJsPath);

  // 引入echart.js
  const echartJsPath = 'js/echart.min.js';
  const echartScript = document.createElement('script');
  echartScript.setAttribute('type', 'text/javascript');
  echartScript.setAttribute('charset', 'utf-8');
  echartScript.src = chrome.extension.getURL(echartJsPath);

  // 引入page.js
  const pageJsPath = 'js/page.js';
  const pageScript = document.createElement('script');
  pageScript.setAttribute('type', 'text/javascript');
  pageScript.setAttribute('charset', 'utf-8');
  pageScript.src = chrome.extension.getURL(pageJsPath);

  // 引入saveFile.js
  const fileSaveJsPath = 'js/fileSave.min.js';
  const fileSaveScript = document.createElement('script');
  fileSaveScript.setAttribute('type', 'text/javascript');
  fileSaveScript.setAttribute('charset', 'utf-8');
  fileSaveScript.src = chrome.extension.getURL(fileSaveJsPath);

  // 引入zip.js
  const zipJsPath = 'js/jszip.min.js';
  const zipScript = document.createElement('script');
  zipScript.setAttribute('type', 'text/javascript');
  zipScript.setAttribute('charset', 'utf-8');
  zipScript.src = chrome.extension.getURL(zipJsPath);
  
  // 修改以下的代码需要同步到content-db.js
  let sellerApp = document.createElement('div');
  sellerApp.id = "dbgj-seller";
  if (window.location.href.indexOf('dabaigongju.com') < 0) {
    // 将上面的文件插入到body中
    document.body.appendChild(jqScript);
    document.body.appendChild(copyScript);
    document.body.appendChild(sellerApp);
    head.appendChild(linkTag);
    document.body.appendChild(hscript);
    jqScript.onload = function() {
      // 必须先引入jq才能引入layer
      document.body.appendChild(qrCodeScript);
      document.body.appendChild(layscript);
      document.body.appendChild(dateScript);
      document.body.appendChild(validScript);
      document.body.appendChild(echartScript);
      document.body.appendChild(pageScript);
      document.body.appendChild(fileSaveScript);
      document.body.appendChild(zipScript);
    }
    layscript.onload = function()
    {
      // 最后引入content-script.js
      setTimeout(function() {
        document.body.appendChild(script);
      }, 500);
    };
  }

  const skuwrap = document.querySelector('.tb-key')
  if (skuwrap) {
    const ttht = document.createElement('div')
    ttht.id = 'dbgjDetails'
    skuwrap.insertBefore(ttht, skuwrap.childNodes[0])
  }

  let hiddenDiv = document.getElementById('dbgjEventDiv');
  if (!hiddenDiv) {
    hiddenDiv = document.createElement('div');
    hiddenDiv.id = "dbgjEventDiv"
    hiddenDiv.style.display = 'none';
    document.body.appendChild(hiddenDiv);
  }

  // 通过 window.postMessage({action: "getToken"}, "*");
  // window.postMessage({action: "setToken", value: token}, '*'); 进行通信

  // 建立长连接
  let port = chrome.runtime.connect({name: 'dbgj'});
  port.onMessage.addListener(function (res) {
    if (res.type === "post") {
      if (res.flag) {
        switch (res.flag) {
          case "get_publicKey":
            dealUpWw(res);
            break;
          case "get_soldHistoryWw":
            dealSoldHistoryWw(res);
            break;
          case "get_soldHistoryWwAgain":
            dealSoldHistoryWwAgain(res);
            break;
          case "get_dropRightOrderStatus":
            dealDropRightOrderStatus(res);
            break;
        }
      }
    }
    else if (res.type === "get") {
      if (res.flag) {
        switch (res.flag) {
          case "get_orderDetailsWw":
            dealOrderDetailsWw(res);
            break;
          case "get_weekSellData": 
            dealWeekSellData(res.data);
            break;
          case "get_dbgjExtInfo": 
            dealFmdsExtInfo(res.data);
            break;
          case "get_punishOrders": 
            dealPunishOrders(res.data);
            break;
          case "get_rDWwTabsCount":
            window.postMessage({
              action: "getRDWwTabsCountCb",
              value: res.data
            }, '*');
            break;
        }
      }
    }
  });

  port.postMessage({action: "getFmdsExtInfo", type: "get", flag: "get_dbgjExtInfo"});
  function dealFmdsExtInfo(data) {
    let dbgjExtInfo = document.createElement('span');
    dbgjExtInfo.id = "dbgj-installed";
    dbgjExtInfo.setAttribute('version', data.dbgjExtVersion);
    dbgjExtInfo.setAttribute('extId', data.dbgjExtId);
    document.body.appendChild(dbgjExtInfo);
  }
  // 获取公钥
  const dbgjUrl = "https://api.dabaigongju.com/plugin";
  function getPublicKey(data) {
    port.postMessage({type: 'post', url: `${dbgjUrl}/getPublicKey`, params: "", flag: "get_publicKey", orginData: data });
  }
  // 上传ww
  function dealUpWw(res){
    let { data, orginData } = res;
    data = JSON.parse(data);
    if (data["code"] === "0") {
      let publicKey = data["data"]
      let enc = new JSEncrypt();
      enc.setPublicKey(publicKey);
      let str = JSON.stringify(orginData.dropRightInfos);
      const encryptedStr = enc.encryptLong(str);
      let uploadData = {
        "dropRightNumber": orginData.dropRightNumber,
        "shopName": orginData.shopName,
        "violationTime": orginData.violationTime,
        "dispositionMode": orginData.dispositionMode,
        "encryptedStr": encryptedStr,
        "publicKey": publicKey
      };
      port.postMessage({type: 'post', url: `${dbgjUrl}/upload/dropRight`, params: uploadData, flag: "", orginData: "" });
    } else {
      return false;
    }
  }

  // 设置号参数去获取订单历史记录
  function setSoldHisQueryAction(obj) {
    const { dropRightNumber, shopName, violationTime, dispositionMode, dropRightInfos } = obj;
    let dropRightNum = dropRightNumber.toString();
    for (let i = 0; i < dropRightInfos.length; i++) {
      (function (i) {
        let oid = dropRightInfos[i].orderNumber;
        setTimeout(function () {
          getSoldHistory(dropRightNum, shopName, violationTime, dispositionMode, oid, "itemlist/SoldHisQueryAction", "before3Months");
        }, i * 1000)
      })(i)
    }
  }
  const asyncSoldUrl = `https://trade.taobao.com/trade/itemlist/asyncSold.do`;
  // 获取订单历史记录，带参数("before3Months")
  function getSoldHistory(drn, sn, vT, dM, oid, action, tabCode) {
    let sold_params = {
      'event_submit_do_query': 1,
      '_input_charset': 'utf8',
      'action': 'itemlist/SoldQueryAction',
      'auctionType': 0,
      'close': 0,
      'dateBegin': 0,
      'dateEnd': 0,
      'pageNum': 1,
      'pageSize': 15,
      'queryMore': false,
      'queryOrder': 'desc',
      'rxAuditFlag': 0,
      'rxElectronicAllFlag': 0,
      'rxElectronicAuditFlag': 0,
      'rxHasSendFlag': 0,
      'rxOldFlag': 0,
      'rxSendFlag': 0,
      'rxSuccessflag': 0,
      'rxWaitSendflag': 0,
      'tradeTag': 0,
      'useCheckcode': false,
      'useOrderInfo': false,
      'errorCheckcode': false,
      'prePageNo': 1
    };
    sold_params['orderId'] = oid;
    if (action) {
      sold_params['action'] = action;
    } 
    if (tabCode) {
      sold_params['tabCode'] = tabCode
    };
    let oData = {"drn": drn, "sn": sn, "vT": vT, "dM": dM, "oid": oid};
    port.postMessage({action: "getSoldHistoryWwPost", type: "post", url: asyncSoldUrl, params: sold_params, flag: "get_soldHistoryWw", orginData: oData});
  }
  // 处理getSoldHistory()请求回来的数据
  function dealSoldHistoryWw(res) {
    const { data, orginData } = res;
    if (data['rgv587_flag'] === 'sm' && data['url']) {
      window.postMessage({
        action: "getStopGetOrderWw",
        value: "stop"
      }, '*');
      return false;
    }
    if (!data['error']) {
      if (data['mainOrders'] && data['mainOrders'].length !== 0) {
        let buyer = data['mainOrders'][0]['buyer'];
        let orderInfo = data['mainOrders'][0]['orderInfo'];
        let ww = buyer['nick'];
        let uid = buyer['id'];
        let createTime = orderInfo['createTime'];
        if (ww && createTime) {
          let postData = {
            "dropRightNumber": orginData.drn,
            "shopName": orginData.sn,
            "violationTime": orginData.vT,
            "dispositionMode": orginData.dM,
            "dropRightInfos": [
              { "orderNumber": orginData.oid, "wangwang": ww }
            ]
          };
          // 有旺旺号就获取公钥加密上传
          getPublicKey(postData);
        } else {
            return false;
        }
      } else {
        // data['mainOrders']为[]时再请求多一遍
        setTimeout(function(){
          getSoldHistoryAgain(orginData.drn, orginData.sn, orginData.vT, orginData.dM, orginData.oid);
        }, 1000);
      }
    } else {
      // 直接请求订单详情页获取旺旺
      getOrderDetailsWw(orginData.drn, orginData.sn, orginData.vT, orginData.dM, orginData.oid);
    }
  }
  // 获取订单历史记录，不带参数("before3Months")362179457281689756
  function getSoldHistoryAgain(drn, sn, vT, dM, oid) {
    let sold_params = {
      'event_submit_do_query': 1,
      '_input_charset': 'utf8',
      'action': 'itemlist/SoldQueryAction',
      'auctionType': 0,
      'close': 0,
      'dateBegin': 0,
      'dateEnd': 0,
      'pageNum': 1,
      'pageSize': 15,
      'queryMore': false,
      'queryOrder': 'desc',
      'rxAuditFlag': 0,
      'rxElectronicAllFlag': 0,
      'rxElectronicAuditFlag': 0,
      'rxHasSendFlag': 0,
      'rxOldFlag': 0,
      'rxSendFlag': 0,
      'rxSuccessflag': 0,
      'rxWaitSendflag': 0,
      'tradeTag': 0,
      'useCheckcode': false,
      'useOrderInfo': false,
      'errorCheckcode': false,
      'prePageNo': 1
    };
    sold_params['orderId'] = oid;
    let oData = {"drn": drn, "sn": sn, "vT": vT, "dM": dM, "oid": oid};
    port.postMessage({action: "getSoldHistoryWwPost", type: "post", url: asyncSoldUrl, params: sold_params, flag: "get_soldHistoryWwAgain", orginData: oData});
  }
  // getSoldHistoryAgain()请求回来的数据
  function dealSoldHistoryWwAgain(res) {
    const { data, orginData } = res;
    if (!data['error']) {
      if (data['mainOrders'] && data['mainOrders'].length) {
        let buyer = data['mainOrders'][0]['buyer'];
        let orderInfo = data['mainOrders'][0]['orderInfo'];
        let ww = buyer['nick'];
        let uid = buyer['id'];
        let createTime = orderInfo['createTime'];
        if (ww && createTime) {
          let postData = {
            "dropRightNumber": orginData.drn,
            "shopName": orginData.sn,
            "violationTime": orginData.vT,
            "dispositionMode": orginData.dM,
            "dropRightInfos": [
              { "orderNumber": orginData.oid, "wangwang": ww }
            ]
          };
          // 有旺旺号就获取公钥加密上传
          getPublicKey(postData);
        } else {
          return false;
        }
      } else {
        return false;
      }
    } else {
      // 直接请求订单详情页获取旺旺
      getOrderDetailsWw(orginData.drn, orginData.sn, orginData.vT, orginData.dM, orginData.oid);
    }
  }
  // 请求订单详情页
  function getOrderDetailsWw(drn, sn, vT, dM, oid) {
    const detailUrl = `https://trade.taobao.com/trade/detail/trade_item_detail.htm?bizOrderId=${oid}`;
    let oData = {"drn": drn, "sn": sn, "vT": vT, "dM": dM, "oid": oid};
    port.postMessage({action: "getOrderDetailsWWGet", type: "get", url: detailUrl, flag: "get_orderDetailsWw", orginData: oData});
  }
  // 处理getOrderDetailsWw()返回的数据
  function dealOrderDetailsWw(res) {
    const { data, orginData } = res;
    let ww_reg = /<span class="nickname">(.*?)<\/span>/ig;
    let ww_ret = ww_reg.exec(data);
    let ww = "";
    if (ww_ret) {
      ww = ww_ret[1];
    }
    if (ww.length !== 0) {
      let postData = { 
        "dropRightNumber": orginData.drn,
        "shopName": orginData.sn,
        "violationTime": orginData.vT,
        "dispositionMode": orginData.dM,
        "dropRightInfos": [
          { "orderNumber": orginData.oid, "wangwang": ww }
        ]
      };
      // 有旺旺号就获取公钥加密上传
      getPublicKey(postData);
    } else {
      return false;
    }
  }

  // 获取30天商品分析数据
  function getWeekSellData(url) {
    port.postMessage({action: "getWeekSellDataGet", type: "get", url: url, flag: "get_weekSellData"});
  }
  // 处理getWeekSellData()返回的数据发送给页面显示
  function dealWeekSellData(data){
    window.postMessage({
      action: "getWeekSellDataCb",
      value: data
    }, '*');
  }

  // 购买记录
  const poUrl=  "https://healthcenter.taobao.com/home/json/get_affect_order_list.do?_x=1";
  function getPunishOrders(data) {
    port.postMessage({action: "getPunishOrdersGet", type: "get", params: data.params, url: poUrl, flag: "get_punishOrders", orginData: data});
  }
  function dealPunishOrders(res) {
    let { result, orginData }  = res;
    let data = result["module"].data;
    let dropRightArr = [];
    if (data.length === 0 || !data.length) {
      return false;
    }
    for(let i = 0; i < data.length; i++) {
      let temp = { "orderNumber": data[i].orderId, "editUrl": `https:${data[i].editUrl}` };
      dropRightArr.push(temp);
    }
    let cbData = {obj: orginData.obj, dropRightArr: dropRightArr};
    window.postMessage({
      action: "getPunishOrdersCb",
      value: cbData
    }, '*');
  }

  // /getDropRightStatus
  function getDropRightOrderStatus(data) {
    const { uploadObj, punishObj } = data;
    port.postMessage({type: "post", url: `${dbgjUrl}/getDropRightStatus`, params: uploadObj, flag: "get_dropRightOrderStatus", orginData: punishObj});
  }
  function dealDropRightOrderStatus(res) {
    const {flag, type, data, orginData} = res;
    let cbData = {data: data, orginData: orginData};
    window.postMessage({
      action: "getDropRightOrderStatusCb",
      value: cbData
    }, '*');
  }

  window.addEventListener("message", function (e) {
    if (e.data.action === "setToken") {
      chrome.storage.sync.set({ token: e.data.value }, function (res) {
        // chrome.storage.sync可以跟随当前登录用户自动同步，这台电脑修改的设置会自动同步到其它电脑
        // 如果没有登录或者未联网则先保存到本地，等登录了再同步至网络；
      });
    } else if (e.data.action === "getToken") {
      chrome.storage.sync.get(['token'], function (result) {
        var customEvent = document.createEvent('Event');
        customEvent.initEvent('dbgjSetTokenEvent', true, true);
        hiddenDiv.innerText = JSON.stringify(result)
        hiddenDiv.dispatchEvent(customEvent);
      });
    } else if (e.data.action === "setRememberPw") {
      chrome.storage.sync.set({ userAccount: e.data.value }, function (res) {
      });
    } else if (e.data.action === "getRememberPw") {
      chrome.storage.sync.get(['userAccount'], function (result) {
        window.postMessage({
          action: "getRememberPwCb",
          value: result
        }, '*');
      });
    } else if (e.data.action === "getDownRightWw") {
      setSoldHisQueryAction(e.data.value)
    } else if (e.data.action === "getWeekSellData") {
      getWeekSellData(e.data.value)
    } else if (e.data.action === "getPunishOrders") {
      getPunishOrders(e.data.value)
    } else if (e.data.action === "getDropRightOrderStatus") {
      getDropRightOrderStatus(e.data.value)
    } else if(e.data.action === "getRDWwTabsCount") {
      port.postMessage({action: "getRDWwTabsCount", type: "get", flag: "get_rDWwTabsCount"});
    } else {
      return false
    }
  })
})();